package com.qintian.rainstorm.test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateFormatUtil {
	
	/**
	 * 
	 * @param dateStr 形如 "20170509200000"的字符串
	 * @return
	 * @throws ParseException
	 */
	public static Date formatToDate(String dateStr ) {
		try {
			StringBuilder buffer = new StringBuilder(dateStr.substring(0, 4) + "-" + 
					dateStr.substring(4, 6) + "-" + dateStr.substring(6, 8) + " " +
					dateStr.substring(8, 10) + ":" + dateStr.substring(10, 12) + ":" +
					dateStr.substring(12, 14));
			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = formatter.parse(buffer.toString());
			return date;
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 *  返回指定小时后的日期对应的字符串（yyyyMMddHHmmss）
	 * @param date 日期
	 * @param hour 指定小时数
	 * @return
	 */
	public static String addHours(Date date,  int hour) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.HOUR, hour);
		Date date2 = calendar.getTime();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		String result = formatter.format(date2);
		return result;
	}
	
	/**
	 *  返回指定小时后的日期对应的字符串（yyyyMMddHH0000）
	 * @param date 日期
	 * @param hour 指定小时数
	 * @return
	 */
	public static String addHours2(Date date,  int hour) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.HOUR, hour);
		Date date2 = calendar.getTime();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHH0000");
		String result = formatter.format(date2);
		return result;
	}
}
